//
//  DingdanViewController.swift
//  联付商圈
//
//  Created by zhangqi on 2017/8/10.
//  Copyright © 2017年 lianfu. All rights reserved.
//

import UIKit
import Alamofire
import Kingfisher



class DingdanViewController: UIViewController {
    
    var textHigh = 80
    var gaoduBtnHid = false
    var liuyan = ""
    var isTarget = true
    var targetRect = CGRect()
    
    var zongdingdan = [String]()
    
    var numtotal = 0
    var numnum = [Int]()
    var idid = [Int]()
    var nana = [String]()
    var jiajia = [Double]()
    var imgimg = [String]()
    
    var danpinzongjia = [Double]()
    
    var numAr = numArr
    var idAr = idArr
    var nameAr = nameArr
    var jiageAr = jiageArr
    var imgAr = imgArr
    
    @IBOutlet weak var dingdanTableView: UITableView!
    
    @IBOutlet weak var xufuLabel: UILabel!
    
    @IBAction func lijizhifuBtn(_ sender: UIButton) {
        //textView.resignFirstResponder()
                if numtotal == 0 {
                    self.noticeInfo("未选择商品", autoClear: true, autoClearTime: 1)
                } else if numtotal > 0 {
        
                    shengchengdingdan2()
                    
                }
    }
    
    func guolv(){
            for y in 0 ..< numAr.count {
                if numAr[y] != 0 {
                    numnum.append(numAr[y])
                    idid.append(idAr[y])
                    nana.append(nameAr[y])
                    jiajia.append(jiageAr[y])
                    imgimg.append(imgAr[y])
            }
        }
    }
    
    
    func tongji(){
        danpinzongjia = [Double]()
        for x in 0 ..< numnum.count {
            let z = Double(numnum[x])
            let a = Double(jiajia[x])
            danpinzongjia.append(z*a)
        }
        numtotal = numnum.reduce(0,{$0 + $1})
        zonghjia = danpinzongjia.reduce(0,{$0 + $1})
        xufuLabel.text = "需付:¥" + "\(zonghjia)"
    }

    
    func shengchengdingdan2(){
        let x = UserDefaults.standard.object(forKey: "userInfo") as? NSDictionary
        if x == nil {
            self.noticeInfo("未登录", autoClear: true, autoClearTime: 1)
        } else if x != nil {
            
        
        //let x = UserDefaults.standard.object(forKey: "userInfo") as! NSDictionary
            let xx = x!
        let y = "\(xx["name"]!)"
        
        let date = NSDate()
        
        let timeFormatter = DateFormatter()
        
        timeFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
        
        let strNowTime = timeFormatter.string(from: date as Date) as String
//print(strNowTime)
        //print(strNowTime)
        if liuyan == "给买家留言，50字以内" {
            liuyan = ""
        }
        let par = ["id":y,"productid":"\(idid)","number":"\(numnum)","name":"\(nana)","price":"\(jiajia)","shop_id":"\(dpid)","created_at":strNowTime,"message":liuyan,"priceall":"\(zonghjia)","payword":"123"] as [String : String]
//        print(par)
//        print(par)
            let manager = Alamofire.SessionManager.default
            manager.session.configuration.timeoutIntervalForRequest = 45
        let urlString = "https://www.beidikeji.com/life/public/jiekou/dingdancreate?"
        manager.request(urlString,method:.post,parameters: par).responseJSON {Request in
            switch Request.result {
            case .success:
                let json = JSON(data: Request.data!)
//                print(json)
//                print(json)
                let x = json["success"].dictionaryObject!
                let dh = x["ddh"]!
                let zj = x["priceall"] as! String
                ddh = "\(dh)"
                zonghjia = Double(zj)!//zj as! Double
                if ddh != "" {
                let sb = UIStoryboard(name: "Main", bundle:nil)
                let secondViewController = sb.instantiateViewController(withIdentifier: "ZhifuViewController") as! ZhifuViewController
                self.navigationController?.pushViewController(secondViewController, animated: true)
                } else if ddh == "" {
                    self.noticeInfo("未知错误", autoClear: true, autoClearTime: 1)
                }
            case .failure:
                self.noticeInfo("未知错误", autoClear: true, autoClearTime: 1)
                let sb = UIStoryboard(name: "Main", bundle:nil)
                let secondViewController = sb.instantiateViewController(withIdentifier: "ZhifuViewController") as! ZhifuViewController
                self.navigationController?.pushViewController(secondViewController, animated: true)
            }
        }
        }
    }

    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        guolv()
        tongji()
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.kbFrameChanged(_:)), name: .UIKeyboardWillChangeFrame, object: nil)
        
        dingdanTableView.tableFooterView = UIView(frame: CGRect.zero)
        
        dingdanTableView.keyboardDismissMode = .onDrag
        dingdanTableView.keyboardDismissMode =  .interactive
        dingdanTableView.showsVerticalScrollIndicator = false
    }

   
    
  
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    

    func kbFrameChanged(_ notification : Notification){
        let info = notification.userInfo
        let kbRect = (info?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let offsetY = kbRect.origin.y - UIScreen.main.bounds.height
        UIView.animate(withDuration: 0.3) {
            self.view.transform = CGAffineTransform(translationX: 0, y: offsetY)
        }
    }
       
    func gaodu(){
        textHigh = 120
        gaoduBtnHid = true
        dingdanTableView.reloadData()
    }
    
    func textqueren(){
        textHigh = 90
        gaoduBtnHid = false
        dingdanTableView.reloadData()
    }
    
    func add(sender: UIButton){
        let x = sender.tag
        numnum[x] += 1
        tongji()
        //shengcheng()
        dingdanTableView.reloadData()
    }
    
    func less(sender: UIButton){
        let x = sender.tag
        numnum[x] -= 1
        if numnum[x] < 0 {
            numnum[x] = 0
        }
        tongji()
        //shengcheng()
        dingdanTableView.reloadData()
    }
    
    
    
   

}

extension DingdanViewController: UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UITextViewDelegate {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 4
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 1
        case 1:
            return nana.count
        case 2:
            return 1
        case 3:
            return 1
        
        default:
            break
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "DianpumingchengTableViewCell", for: indexPath) as! DianpumingchengTableViewCell
            cell.dianpuNameLabel.text = shangdianming
            return cell
        } else if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ShangpinliebiaoTableViewCell", for: indexPath) as! ShangpinliebiaoTableViewCell
            cell.addBtn.tag = indexPath.row
            cell.lessBtn.tag = indexPath.row
            //cell.shangpinImage.layer.cornerRadius = 12.0
            cell.shangpinNameLabel.text = nana[indexPath.row]
            cell.jiageLabel.text = "¥" + "\(jiajia[indexPath.row])"
            cell.shuliangLabel.text = "\(numnum[indexPath.row])"
            cell.addBtn.addTarget(self, action:#selector(DingdanViewController.add), for: .touchUpInside)
            cell.lessBtn.addTarget(self, action:#selector(DingdanViewController.less), for: .touchUpInside)
            self.setup(cell: cell, atIndexPath: indexPath)
            return cell
        } else if indexPath.section == 2 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "LiuyanTableViewCell", for: indexPath) as! LiuyanTableViewCell
            liuyan = cell.liuyanText.text
            cell.gaoduBtn.addTarget(self, action: #selector(DingdanViewController.gaodu), for: .touchUpInside)
            cell.querenBtn.addTarget(self, action: #selector(DingdanViewController.textqueren), for: .touchUpInside)
            if gaoduBtnHid == false {
                cell.gaoduBtn.isHidden = false
                cell.querenBtn.isHidden = true
            } else if gaoduBtnHid == true {
                cell.gaoduBtn.isHidden = true
                cell.liuyanText.text = ""
                //cell.liuyanText.//beginningOfDocument
                cell.querenBtn.isHidden = false
            }
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ZongjijiageTableViewCell", for: indexPath) as! ZongjijiageTableViewCell
            cell.jiageLabel.text = "共计" + "\(numtotal)" + "件商品 合计:¥" + "\(zonghjia)"
            return cell
            
        }
    }
    
    
    
    func setup(cell: ShangpinliebiaoTableViewCell, atIndexPath indexPath: IndexPath) {
        let  or = imgimg[indexPath.row]
        let url = URL(string:or)
        if cell.shangpinImage.kf.webURL != url {
            let cellFrame = self.dingdanTableView.rectForRow(at: indexPath)
            var shouldLoadImage = true
            if self.isTarget && !self.targetRect.intersects(cellFrame) {
                let image = KingfisherManager.shared.cache.retrieveImageInDiskCache(forKey: or, options: nil)
                if image == nil {
                    shouldLoadImage = false
                }
            }
            if shouldLoadImage {
                cell.shangpinImage.kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: nil, completionHandler: { (image, error, type, urls) in
                    if error == nil && url == urls {
                    }})}
            
        }}


    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 1 {
            return 90
        } else if indexPath.section == 2 {
            return CGFloat(textHigh)
        } else {
            return 44
        }
    }
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            return 20
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        UIView.animate(withDuration: 0.3) {
            self.view.transform = CGAffineTransform(translationX: 0, y: 0)
            self.view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
        }
        return true
    }
    
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if (text == "\n") {
            textView.resignFirstResponder()
            UIView.animate(withDuration: 0.3) {
                self.view.transform = CGAffineTransform(translationX: 0, y: 0)
                self.view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
            }
            return false
        }
        return true
    }

    
    
    
}
